import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRoute, anyRoute, asnycRoute } from '@/router/routes'
import type { UserState } from './types/types'
import type { loginFormData, loginResponseData, userInfoResponseData } from '@/api/user/type'
import { cloneDeep } from 'lodash'
import router from '@/router'

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
const useUserStore = defineStore('User', {
  state: () => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      userName: '',
      userData: {},
      //存储当前用户是否包含某一个按钮
      buttons: []
    }
  },
  getters: {
    getUserInfo: (state) => {
      return state
    }
  },
  actions: {
    async userLogin(data: loginFormData) {
      const res: loginResponseData = await reqLogin(data)
      if (res.code === 200) {
        this.token = <string>res.data
        SET_TOKEN(<string>res.data)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data as string))
      }
    },
    async userInfo() {
      const res: userInfoResponseData = await reqUserInfo()
      if (res.code === 200) {
        this.userData = res.data
        this.userName = res.data.name
        this.buttons = res.data.buttons
        //计算当前用户需要展示的异步路由
        const userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), res.data.routes)
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message as string))
      }
    },
    async userLogout() {
      const res: any = await reqLogout()
      if (res.code === 200) {
        this.token = null
        this.userData = {}
        this.userName = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    }
  }
})
export default useUserStore
